#include "Cannon.h"
#include "StaticData.h"
USING_NS_CC;
Cannon::Cannon():_type(k_Cannon_Type_Invalid)
{
}

Cannon::~Cannon()
{
	if(_canonSprites)
		_canonSprites->release();
}

Cannon* Cannon::create(CannonType type/*=k_Cannon_Type_1*/)
{
	Cannon* cannon=new Cannon;
	cannon->init(type);
	cannon->autorelease();
	return cannon;
}

bool Cannon::init(CannonType type/*=k_Cannon_Type_1*/)
{
	_canonSprites=CCArray::createWithCapacity(k_Cannon_Type_Count);
	_canonSprites->retain();
	CCPoint authorPoints(0.5,0.26);
	for(int i=k_Cannon_Type_1;i<k_Cannon_Type_Count;i++)
	{
		CCString* fileName=CCString::createWithFormat(StaticData::getInstance()->stringFromKey("cannon_level_name_format"),i+1);
		CCSprite* canonSprite=CCSprite::createWithSpriteFrameName(fileName->getCString());
		canonSprite->setAnchorPoint(authorPoints);
		_canonSprites->addObject(canonSprite);
	}
	setType(type);
	return true;
}

CCSprite* Cannon::getCurCannonSprite()
{
	return static_cast<CCSprite*>(_canonSprites->objectAtIndex(_type));
}

void Cannon::setType(CannonType type)
{
	if(_type==type)
		return;
	if(type>=k_Cannon_Type_Count)
		type=k_Cannon_Type_1;
	else if(type<k_Cannon_Type_1)
		type=k_Cannon_Type_2;
	removeChildByTag(_type,false);
	CCSprite* newCanonSprite=static_cast<CCSprite*>(_canonSprites->objectAtIndex(type));
	addChild(newCanonSprite,0,type);
	_type=type;
}

void Cannon::aimAt(CCPoint target)
{
	CCPoint location=getParent()->convertToWorldSpace(getPosition());
	float angle=ccpAngleSigned(ccpSub(target,location),CCPoint(0,1));
	setRotation(CC_RADIANS_TO_DEGREES(angle));
}
